package me.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * 数据库连接池
 */
public class DBManager {


    //定义数据资源
    private static DataSource dataSource;

    /**
     * 加载静态代码块
     */
    static {
        //实例化属性文件
        Properties properties = new Properties();
        //获取配置文件
        InputStream is = DBManager.class.getClassLoader().getResourceAsStream("druid.properties");

        try {
            //加载配置文件
            properties.load(is);
            //通过配置文件获取数据库资源DataSource
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取数据资源
     * @return
     */
    public static DataSource getDataSource(){
        return dataSource;
    }

    /**
     * 获取连接对象
     * @return
     */
    public static Connection getConnection() throws SQLException {

        return getDataSource().getConnection();
    }

}
